#!/bin/bash
# glibc_run.sh
# 执行glibc2.28环境下的命令
# practice eg:
# bash glibc_run.sh  --glibc  "/usr/local/glibc"  --cmd  "python -m pip install --no-index --find-links=./additional_deps/dependencies -r ./additional_deps/requirements-linux-cpu.txt"

set -e

GLIBC_ROOT=""
CMD_ARGS=""
CMD_STRING=""

# 解析命令行参数，获得glibc路径和命令
while [[ $# -gt 0 ]]; do
    case "$1" in
    --glibc)
        GLIBC_ROOT="$2"
        shift 2
        ;;
    --cmd)
        CMD_STRING="$2"
        shift 2
        ;;
    *)
        echo "未知参数: $1"
        exit 1
        ;;
    esac
done

# 如果入参未指定，选用脚本目录安装的glibc2.28
if [ -z "$GLIBC_ROOT" ]; then
    echo "未指定glibc路径，使用默认路径: $(pwd)/additional_deps/installed_deps/glibc-2.28"
    GLIBC_ROOT="$(pwd)/additional_deps/installed_deps/glibc-2.28"
fi
echo "using glibc root: $GLIBC_ROOT"

# 设置环境变量
export PATH="$GLIBC_ROOT/bin:$PATH"
echo "current PATH is: $PATH"

# 1. # 如果openssl未安装在系统标准位置（/usr/lib64），则手动修改openssl库地址
OPENSSL_LIB="/usr/local/openssl/lib" # 替换为您的实际路径

# 读取环境变量CUSTOM_OPENSSL_LIB 获取openssl库地址
echo "Custom OpenSSL library path: $CUSTOM_OPENSSL_LIB"

# 2. 创建库路径数组，确保顺序正确
LIB_PATHS=(
    "$GLIBC_ROOT/lib"     # glibc 库
    "${OPENSSL_LIB}"      # 高版本 OpenSSL 优先
    "$CUSTOM_OPENSSL_LIB" # 可选的环境变量 OpenSSL 库路径
    "/usr/lib64"          # 系统库,必须
)

# 3. 过滤掉不存在的路径
VALID_PATHS=()
for path in "${LIB_PATHS[@]}"; do
    if [ -d "$path" ]; then
        VALID_PATHS+=("$path")
        echo "Found library path: $path"
    fi
done

# 4. 拼接为冒号分隔的路径
LIBRARY_PATH=$(
    IFS=:
    echo "${VALID_PATHS[*]}"
)
echo "Final LIBRARY_PATH: $LIBRARY_PATH"

# 5. 执行命令

# 4. 安全地将命令字符串转换为数组
# 使用 eval 和数组来正确处理带空格和引号的参数
eval "CMD_ARGS=($CMD_STRING)"

echo "Running in glibc2.28 environment:"
echo "Executing command: ${CMD_ARGS[*]}"

$GLIBC_ROOT/lib/ld-linux-aarch64.so.1 \
    --inhibit-cache \
    --library-path "$LIBRARY_PATH" \
    "${CMD_ARGS[@]}"
